package com.example.demo2.Util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
@Component
public class FileUtil {
    @Value("${path.absolutePath}")
    public  String absolutePath;
    @Value("${path.urlPath}")
    public  String urlPath;
    public String   save(MultipartFile  file){//a.png  a.png .jpg
        try {
            //获取原来的名字
            String fileName=file.getOriginalFilename();
            //图片名要是唯一
            String  newFileName= UUID.randomUUID().toString().replace("-","")+ fileName.substring(fileName.lastIndexOf("."));
            //保存
            file.transferTo(new File(absolutePath,newFileName));
            return  urlPath+newFileName;
        } catch (IOException e) {
            //自定义异常
            throw new RuntimeException(e);
        }
    }

    public String   save(String folderPath,MultipartFile  multipartFile){//a.png  a.png .jpg
        if(!folderPath.endsWith("/")){
            folderPath=folderPath+"/";
        }
        try {
            //获取原来的名字
            String fileName=multipartFile.getOriginalFilename();
            //图片名要是唯一
            String  newFileName= UUID.randomUUID().toString()+ fileName.substring(fileName.lastIndexOf("."));
            //创建文件的新路径
            File file=new File(absolutePath,folderPath);
            if(!file.exists()){//不可执行  该路径不存在
                file.mkdirs();//创建文件夹
            }
            //保存
            multipartFile.transferTo(new File(file,newFileName));
            return  urlPath+folderPath+newFileName;
        } catch (IOException e) {
            //自定义异常
            throw new RuntimeException(e);
        }
    }
}
